import { 
  DataInsightParams, 
  DataInsightResponse, 
  CategoryData, 
  WarehouseStats, 
  MaterialInsight,
  TimeRange,
  AnalysisDimension
} from '@/types/warehouse'

/**
 * 数据洞察服务类
 * 提供数据获取、处理和缓存功能
 */
export class DataInsightService {
  private static instance: DataInsightService
  private cache: Map<string, any> = new Map()
  private cacheTimeout = 5 * 60 * 1000 // 5分钟缓存

  /**
   * 获取单例实例
   */
  public static getInstance(): DataInsightService {
    if (!DataInsightService.instance) {
      DataInsightService.instance = new DataInsightService()
    }
    return DataInsightService.instance
  }

  /**
   * 获取数据洞察概览
   */
  async getDataInsightOverview(params: DataInsightParams): Promise<DataInsightResponse> {
    const cacheKey = `overview_${JSON.stringify(params)}`
    
    if (this.isCacheValid(cacheKey)) {
      return this.cache.get(cacheKey)
    }

    try {
      const response = await this.fetchData('/api/data-insights/overview', params)
      const processedData = this.processOverviewData(response.data)
      
      this.setCache(cacheKey, processedData)
      return processedData
    } catch (error) {
      console.error('获取数据洞察概览失败:', error)
      throw this.createErrorResponse('获取数据失败，请稍后重试')
    }
  }

  /**
   * 获取库存趋势数据
   */
  async getInventoryTrend(params: {
    timeRange: TimeRange
    warehouseIds?: string[]
    materialTypes?: string[]
  }) {
    const cacheKey = `trend_${JSON.stringify(params)}`
    
    if (this.isCacheValid(cacheKey)) {
      return this.cache.get(cacheKey)
    }

    try {
      const response = await this.fetchData('/api/data-insights/trend', params)
      const processedData = this.processTrendData(response.data)
      
      this.setCache(cacheKey, processedData)
      return processedData
    } catch (error) {
      console.error('获取库存趋势数据失败:', error)
      throw this.createErrorResponse('获取趋势数据失败')
    }
  }

  /**
   * 获取分类占比数据
   */
  async getCategoryDistribution(params: {
    dimension: AnalysisDimension
    warehouseIds?: string[]
    dateRange?: [string, string]
  }) {
    const cacheKey = `category_${JSON.stringify(params)}`
    
    if (this.isCacheValid(cacheKey)) {
      return this.cache.get(cacheKey)
    }

    try {
      const response = await this.fetchData('/api/data-insights/category', params)
      const processedData = this.processCategoryData(response.data)
      
      this.setCache(cacheKey, processedData)
      return processedData
    } catch (error) {
      console.error('获取分类占比数据失败:', error)
      throw this.createErrorResponse('获取分类数据失败')
    }
  }

  /**
   * 获取预警信息
   */
  async getWarningInfo(params: {
    levels?: string[]
    warehouseIds?: string[]
    limit?: number
  }) {
    const cacheKey = `warnings_${JSON.stringify(params)}`
    
    if (this.isCacheValid(cacheKey)) {
      return this.cache.get(cacheKey)
    }

    try {
      const response = await this.fetchData('/api/data-insights/warnings', params)
      const processedData = this.processWarningData(response.data)
      
      this.setCache(cacheKey, processedData)
      return processedData
    } catch (error) {
      console.error('获取预警信息失败:', error)
      throw this.createErrorResponse('获取预警信息失败')
    }
  }

  /**
   * 获取热门物料排行
   */
  async getTopMaterials(params: {
    limit?: number
    sortBy?: 'stock' | 'turnover' | 'revenue'
    warehouseIds?: string[]
  }) {
    const cacheKey = `materials_${JSON.stringify(params)}`
    
    if (this.isCacheValid(cacheKey)) {
      return this.cache.get(cacheKey)
    }

    try {
      const response = await this.fetchData('/api/data-insights/top-materials', params)
      const processedData = this.processMaterialData(response.data)
      
      this.setCache(cacheKey, processedData)
      return processedData
    } catch (error) {
      console.error('获取热门物料排行失败:', error)
      throw this.createErrorResponse('获取物料数据失败')
    }
  }

  /**
   * 获取智能建议
   */
  async getSmartSuggestions(params: {
    warehouseIds?: string[]
    materialTypes?: string[]
    priority?: 'high' | 'medium' | 'low'
  }) {
    const cacheKey = `suggestions_${JSON.stringify(params)}`
    
    if (this.isCacheValid(cacheKey)) {
      return this.cache.get(cacheKey)
    }

    try {
      const response = await this.fetchData('/api/data-insights/suggestions', params)
      const processedData = this.processSuggestionData(response.data)
      
      this.setCache(cacheKey, processedData)
      return processedData
    } catch (error) {
      console.error('获取智能建议失败:', error)
      throw this.createErrorResponse('获取建议失败')
    }
  }

  /**
   * 获取物料详情
   */
  async getMaterialDetail(materialId: string) {
    const cacheKey = `material_${materialId}`
    
    if (this.isCacheValid(cacheKey)) {
      return this.cache.get(cacheKey)
    }

    try {
      const response = await this.fetchData(`/api/data-insights/material/${materialId}`)
      const processedData = this.processMaterialDetail(response.data)
      
      this.setCache(cacheKey, processedData)
      return processedData
    } catch (error) {
      console.error('获取物料详情失败:', error)
      throw this.createErrorResponse('获取物料详情失败')
    }
  }

  /**
   * 导出数据洞察报告
   */
  async exportDataInsight(params: DataInsightParams, format: 'excel' | 'pdf' | 'csv') {
    try {
      const response = await this.fetchData('/api/data-insights/export', {
        ...params,
        format
      })
      
      return {
        url: response.data.url,
        filename: response.data.filename,
        size: response.data.size
      }
    } catch (error) {
      console.error('导出数据洞察报告失败:', error)
      throw this.createErrorResponse('导出失败')
    }
  }

  /**
   * 获取实时数据更新
   */
  async getRealtimeUpdate(params: {
    lastUpdateTime: string
    warehouseIds?: string[]
  }) {
    try {
      const response = await this.fetchData('/api/data-insights/realtime', params)
      return response.data
    } catch (error) {
      console.error('获取实时更新失败:', error)
      return null // 静默失败，不影响用户体验
    }
  }

  /**
   * 清除缓存
   */
  clearCache() {
    this.cache.clear()
  }

  /**
   * 私有方法：获取缓存
   */
  private getCache(key: string): any {
    const cached = this.cache.get(key)
    if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
      return cached.data
    }
    return null
  }

  /**
   * 私有方法：设置缓存
   */
  private setCache(key: string, data: any) {
    this.cache.set(key, {
      data,
      timestamp: Date.now()
    })
  }

  /**
   * 私有方法：检查缓存有效性
   */
  private isCacheValid(key: string): boolean {
    const cached = this.cache.get(key)
    return cached && Date.now() - cached.timestamp < this.cacheTimeout
  }

  /**
   * 私有方法：获取数据
   */
  private async fetchData(endpoint: string, params?: any) {
    // 模拟API调用，实际项目中替换为真实的HTTP请求
    return this.mockApiCall(endpoint, params)
  }

  /**
   * 私有方法：处理概览数据
   */
  private processOverviewData(data: any): DataInsightResponse {
    return {
      totalInventory: data.totalInventory || 0,
      totalValue: data.totalValue || 0,
      totalItems: data.totalItems || 0,
      activeWarnings: data.activeWarnings || 0,
      turnoverRate: data.turnoverRate || 0,
      dailyAvg: data.dailyAvg || 0,
      trend: data.trend || [],
      categories: data.categories || [],
      warehouses: data.warehouses || [],
      materials: data.materials || [],
      warnings: data.warnings || [],
      suggestions: data.suggestions || [],
      lastUpdated: new Date().toISOString()
    }
  }

  /**
   * 私有方法：处理趋势数据
   */
  private processTrendData(data: any) {
    return {
      labels: data.labels || [],
      datasets: data.datasets || [],
      summary: data.summary || {}
    }
  }

  /**
   * 私有方法：处理分类数据
   */
  private processCategoryData(data: any): CategoryData[] {
    return (data.categories || []).map((item: any) => ({
      name: item.name || '',
      value: item.value || 0,
      percentage: item.percentage || 0,
      color: item.color || '#3b82f6'
    }))
  }

  /**
   * 私有方法：处理预警数据
   */
  private processWarningData(data: any) {
    return (data.warnings || []).map((warning: any) => ({
      id: warning.id || '',
      level: warning.level || 'info',
      title: warning.title || '',
      description: warning.description || '',
      count: warning.count || 0,
      timestamp: warning.timestamp || new Date().toISOString(),
      actions: warning.actions || []
    }))
  }

  /**
   * 私有方法：处理物料数据
   */
  private processMaterialData(data: any) {
    return (data.materials || []).map((material: any) => ({
      id: material.id || '',
      name: material.name || '',
      spec: material.spec || '',
      stock: material.stock || 0,
      unit: material.unit || '',
      turnover: material.turnover || 0,
      revenue: material.revenue || 0,
      lastUpdate: material.lastUpdate || new Date().toISOString()
    }))
  }

  /**
   * 私有方法：处理建议数据
   */
  private processSuggestionData(data: any) {
    return (data.suggestions || []).map((suggestion: any) => ({
      id: suggestion.id || '',
      priority: suggestion.priority || 'medium',
      title: suggestion.title || '',
      description: suggestion.description || '',
      icon: suggestion.icon || '💡',
      actionText: suggestion.actionText || '查看详情',
      impact: suggestion.impact || 0,
      confidence: suggestion.confidence || 0
    }))
  }

  /**
   * 私有方法：处理物料详情
   */
  private processMaterialDetail(data: any) {
    return {
      id: data.id || '',
      code: data.code || '',
      name: data.name || '',
      spec: data.spec || '',
      category: data.category || '',
      stock: data.stock || 0,
      unit: data.unit || '',
      price: data.price || 0,
      value: data.value || 0,
      turnover: data.turnover || 0,
      lastUpdate: data.lastUpdate || new Date().toISOString(),
      trend: data.trend || [],
      warehouses: data.warehouses || [],
      suppliers: data.suppliers || []
    }
  }

  /**
   * 私有方法：创建错误响应
   */
  private createErrorResponse(message: string) {
    return new Error(message)
  }

  /**
   * 私有方法：模拟API调用
   */
  private async mockApiCall(endpoint: string, params?: any) {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500 + Math.random() * 1000))

    // 根据端点返回模拟数据
    const mockData = this.generateMockData(endpoint, params)
    
    return {
      success: true,
      data: mockData,
      message: 'Success'
    }
  }

  /**
   * 私有方法：生成模拟数据
   */
  private generateMockData(endpoint: string, params?: any) {
    switch (endpoint) {
      case '/api/data-insights/overview':
        return {
          totalInventory: 2847500,
          totalValue: 12850000,
          totalItems: 156,
          activeWarnings: 23,
          turnoverRate: 3.2,
          dailyAvg: 156,
          trend: [
            { date: '2024-01-01', inventory: 2800000, value: 12600000 },
            { date: '2024-01-02', inventory: 2820000, value: 12700000 },
            { date: '2024-01-03', inventory: 2847500, value: 12850000 }
          ],
          categories: [
            { name: '螺纹钢', value: 1250000, percentage: 43.9 },
            { name: '盘螺', value: 850000, percentage: 29.8 },
            { name: '角钢', value: 420000, percentage: 14.7 },
            { name: '工字钢', value: 327500, percentage: 11.5 }
          ],
          warehouses: [
            { name: '主仓库', inventory: 1500000, value: 6750000 },
            { name: '原材料库', inventory: 847500, value: 3813750 },
            { name: '成品库', inventory: 500000, value: 2250000 }
          ],
          materials: [
            { id: '1', name: '螺纹钢 HRB400', spec: 'Φ12*12000', stock: 1250, unit: '件', turnover: 85.3 },
            { id: '2', name: '螺纹钢 HRB400', spec: 'Φ16*12000', stock: 890, unit: '件', turnover: 72.1 },
            { id: '3', name: '盘螺 HRB400', spec: 'Φ8*1000', stock: 650, unit: '件', turnover: 68.5 }
          ],
          warnings: [
            { id: '1', level: 'warning', title: '低库存预警', description: '螺纹钢HRB400库存低于安全线', count: 15 },
            { id: '2', level: 'danger', title: '临期物料', description: '角钢Q235即将超过保质期', count: 5 },
            { id: '3', level: 'info', title: '滞销物料', description: '工字钢Q235超过30天无出入库', count: 3 }
          ],
          suggestions: [
            { id: '1', priority: 'high', title: '库存优化', description: '螺纹钢HRB400库存偏高，建议减少采购量20%', icon: '📈' },
            { id: '2', priority: 'medium', title: '周转率提升', description: '角钢类物料周转率偏低，建议优化采购策略', icon: '⚡' },
            { id: '3', priority: 'low', title: '仓库优化', description: '成品库利用率已达92%，建议扩容或调整布局', icon: '🎯' }
          ],
          lastUpdated: new Date().toISOString()
        }

      case '/api/data-insights/trend':
        return {
          labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
          datasets: [
            {
              label: '库存量',
              data: [2800000, 2750000, 2847500, 2900000, 2850000, 2847500],
              borderColor: '#3b82f6',
              backgroundColor: 'rgba(59, 130, 246, 0.1)'
            },
            {
              label: '库存价值',
              data: [12600000, 12375000, 12850000, 13050000, 12825000, 12850000],
              borderColor: '#10b981',
              backgroundColor: 'rgba(16, 185, 129, 0.1)'
            }
          ],
          summary: {
            avg: 2832500,
            max: 2900000,
            min: 2750000,
            trend: 1.7
          }
        }

      case '/api/data-insights/category':
        return {
          categories: [
            { name: '螺纹钢', value: 1250000, percentage: 43.9, color: '#3b82f6' },
            { name: '盘螺', value: 850000, percentage: 29.8, color: '#10b981' },
            { name: '角钢', value: 420000, percentage: 14.7, color: '#f59e0b' },
            { name: '工字钢', value: 327500, percentage: 11.5, color: '#8b5cf6' },
            { name: '其他', value: 10000, percentage: 0.4, color: '#64748b' }
          ]
        }

      case '/api/data-insights/warnings':
        return {
          warnings: [
            { id: '1', level: 'warning', title: '低库存预警', description: '螺纹钢HRB400库存低于安全线', count: 15, timestamp: new Date().toISOString(), actions: [{ id: '1', label: '查看详情' }] },
            { id: '2', level: 'danger', title: '临期物料', description: '角钢Q235即将超过保质期', count: 5, timestamp: new Date().toISOString(), actions: [{ id: '1', label: '查看详情' }] },
            { id: '3', level: 'info', title: '滞销物料', description: '工字钢Q235超过30天无出入库', count: 3, timestamp: new Date().toISOString(), actions: [{ id: '1', label: '查看详情' }] }
          ]
        }

      case '/api/data-insights/top-materials':
        return {
          materials: [
            { id: '1', name: '螺纹钢 HRB400', spec: 'Φ12*12000', stock: 1250, unit: '件', turnover: 85.3, revenue: 5625000 },
            { id: '2', name: '螺纹钢 HRB400', spec: 'Φ16*12000', stock: 890, unit: '件', turnover: 72.1, revenue: 4005000 },
            { id: '3', name: '盘螺 HRB400', spec: 'Φ8*1000', stock: 650, unit: '件', turnover: 68.5, revenue: 2925000 },
            { id: '4', name: '角钢 Q235', spec: '50*50*5', stock: 320, unit: '件', turnover: 45.2, revenue: 1440000 },
            { id: '5', name: '工字钢 Q235', spec: '20#', stock: 180, unit: '件', turnover: 38.7, revenue: 810000 }
          ]
        }

      case '/api/data-insights/suggestions':
        return {
          suggestions: [
            { id: '1', priority: 'high', title: '库存优化', description: '螺纹钢HRB400库存偏高，建议减少采购量20%', icon: '📈', impact: 85, confidence: 92 },
            { id: '2', priority: 'medium', title: '周转率提升', description: '角钢类物料周转率偏低，建议优化采购策略', icon: '⚡', impact: 65, confidence: 78 },
            { id: '3', priority: 'low', title: '仓库优化', description: '成品库利用率已达92%，建议扩容或调整布局', icon: '🎯', impact: 45, confidence: 88 }
          ]
        }

      case '/api/data-insights/material/1':
        return {
          id: '1',
          code: 'HRB400-12-12000',
          name: '螺纹钢 HRB400',
          spec: 'Φ12*12000',
          category: '螺纹钢',
          stock: 1250,
          unit: '件',
          price: 4500,
          value: 5625000,
          turnover: 85.3,
          lastUpdate: new Date().toISOString(),
          trend: [
            { date: '2024-01-01', stock: 1350, value: 6075000 },
            { date: '2024-01-02', stock: 1300, value: 5850000 },
            { date: '2024-01-03', stock: 1250, value: 5625000 }
          ],
          warehouses: [
            { name: '主仓库', stock: 750, value: 3375000 },
            { name: '原材料库', stock: 500, value: 2250000 }
          ],
          suppliers: [
            { name: '供应商A', stock: 800, value: 3600000 },
            { name: '供应商B', stock: 450, value: 2025000 }
          ]
        }

      case '/api/data-insights/export':
        return {
          url: 'https://example.com/downloads/data-insights-report.xlsx',
          filename: `数据洞察报告_${new Date().toISOString().split('T')[0]}.xlsx`,
          size: 256000
        }

      case '/api/data-insights/realtime':
        return {
          hasUpdate: Math.random() > 0.8,
          updates: [
            { type: 'inventory', materialId: '1', change: -50, newValue: 1200 },
            { type: 'warning', warningId: '1', change: -1, newValue: 14 }
          ]
        }

      default:
        return {}
    }
  }
}

// 导出服务实例
export const dataInsightService = DataInsightService.getInstance()